//
//  BTEHomeViewController.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/5.
//

import UIKit

class BTEMeViewController: BTEBaseViewController {
    
    fileprivate let server = BTEMeToolNetServer()
    
    fileprivate var model: BTEMEModel? {
        didSet {
            guard let m = model else {
                return
            }
            v.model = m
        }
    }
    
    var v: BTEMeView {
        return view as! BTEMeView
    }
    
    override func loadView() {
        view = BTEMeView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        updateNavigationTitle(BTELanguageManager.shared.localizedString(forKey: "My"))
        
        view.backgroundColor = .white
        
        v.action = {[weak self] itx in
            self?.click(itx)
        }
        
        v.list.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(navigationBar.snp.bottom)
            let keyWindow = UIApplication.shared.connectedScenes
                   .compactMap { $0 as? UIWindowScene }
                   .flatMap { $0.windows }
                   .first { $0.isKeyWindow }

               let bottomInset = keyWindow?.safeAreaInsets.bottom ?? 0
            make.bottom.equalToSuperview().offset(-(bottomInset+63))
        }

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadModel()
    }
    
    fileprivate func click(_ ind: Int) {
        if let url = model?.vincents?[ind].vyner {
            BTEUrlToolsManager.shared.handleURL(url, in: self, model: model)
        }
    }
    
    fileprivate func loadModel(){
        BTEHUD.shared.showLoader(on: view)
        server.Carneol {[weak self] result in
            switch result {
            case .success(let success):
                BTEHUD.shared.hide()
                self?.model = success?.sidelingwise
                break
            case .failure(let failure):
                switch failure {
                case .Error(c: let b, m: let bd):
                    BTEHUD.shared.showError(bd, on: (self?.view)!)
                    break
                default:
                    break
                }
                break
            }
        }
    }
    

}
